package com.woniuxy.redis;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author: 马宇航
 * @Todo: redis的配置类
 * @DateTime: 22/02/28/0028 下午 4:40
 * @Component: 成都蜗牛学苑
 **/
@Configuration
@EnableCaching //开启缓存
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * redisTemplate配置 这个是直接可以调用redis方法来执行业务
     * ChangeLog : 1. 创建 (22/02/28/0028 下午 4:43 [马宇航]);
     * @param redisConnectionFactory Spring自动帮忙注入的连接工厂
     * @return org.springframework.data.redis.core.RedisTemplate
    */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        //创建redistemplate对象
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //需要配置传入对象的序列化和反序列化
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.json());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        return redisTemplate;
    }
    /**
     * 配置SpringCache整合redis的配置 SpringCache是Spring自带的缓存模块，内部提供了很多缓存接口，
     * 我们这里用的是redis来实现的缓存！ 注解缓存使用的！
     * ChangeLog : 1. 创建 (22/02/28/0028 下午 4:47 [马宇航]);
     *
     * @return org.springframework.data.redis.cache.RedisCacheConfiguration
    */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        //使用默认缓存配置
        //和配置序列化方案
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return redisCacheConfiguration;
    }
}
